﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class MapCreation : MonoBehaviour {

	//游戏地图组件
	//0:老家,1:墙,2:障碍,3:出生效果,4:河流,5:草,6:空气墙
	public GameObject[] Item;

	//已经有东西的位置列表
	//游戏物体的位置保存起来, 之后产生随机位置有没有位置
	public List<Vector3> itemPositionList = new List<Vector3>();

	private void Awake()
	{
		//老窝
		createItem(Item[0], new Vector3(0, -8, 0), Quaternion.identity);
		//用墙把老家围起来
		createItem(Item[1], new Vector3(-1, -8, 0), Quaternion.identity);
		createItem(Item[1], new Vector3(1, -8, 0), Quaternion.identity);
		for (int i = -1; i < 2; i++)
		{
			createItem(Item[1], new Vector3(i, -7, 0), Quaternion.identity);
		}
		//外围空气墙,上下
		for (int i = -11; i < 12; i++)
		{
			//
			createItem(Item[6], new Vector3(i, 9, 0), Quaternion.identity);
			createItem(Item[6], new Vector3(i, -9, 0), Quaternion.identity);
		}
		//外围空气墙,左右
		for (int i = -8; i < 9; i++)
		{
			createItem(Item[6], new Vector3(-11, i, 0), Quaternion.identity);
			createItem(Item[6], new Vector3(11, i, 0), Quaternion.identity);
		}
		//实例化玩家
		GameObject gamePlayer1 = Instantiate(Item[3], new Vector3(-2,-8,0), Quaternion.identity);
		gamePlayer1.GetComponent<Born>().createPlayer = true;

		//实例化敌人
		createItem(Item[3], new Vector3(-10, 8, 0), Quaternion.identity);
		createItem(Item[3], new Vector3(0, 8, 0), Quaternion.identity);
		createItem(Item[3], new Vector3(10, 8, 0), Quaternion.identity);
		InvokeRepeating("createEnemy",4,5);

		//实例化地图
		//墙
		for (int i = 0; i < 20; i++)
		{	
			//墙多一点跟其他占比为3:1
			createItem(Item[1], createRandomPosition(), Quaternion.identity);
			createItem(Item[1], createRandomPosition(), Quaternion.identity);
			createItem(Item[1], createRandomPosition(), Quaternion.identity);

			createItem(Item[2], createRandomPosition(), Quaternion.identity);
			createItem(Item[4], createRandomPosition(), Quaternion.identity);
			createItem(Item[5], createRandomPosition(), Quaternion.identity);
		}
	}

	private void createItem(GameObject item, Vector3 position, Quaternion ratation) {
		GameObject itemGo = Instantiate(item, position, ratation);
		itemGo.transform.SetParent(gameObject.transform);
		itemPositionList.Add(position);
	}

	//如果位置存在, 不使用重新生成
	private Vector3 createRandomPosition() {
		//敌人的位置,最外围不产生障碍,防止产生障碍导致无法进攻
		//不生成x=10,y=-10,y=8,y=-8这两行的位置
		while (true) {
			//产生一个随机位置
			Vector3 ver3 = new Vector3(Random.Range(-9,10), Random.Range(-7,8), 0);
			if (!itemPositionList.Contains(ver3)) {
				return ver3;
			}
		}
	}
	//产生随机敌人的方法
	private void createEnemy() {
		if (PlayerManager.Instance.isDefeat)
		{
			return;
		}
		int num = Random.Range(0, 3);
		Vector3 enemyPos;
		if (num == 0) {
			enemyPos = new Vector3(-10, 8, 0);
		} else if (num == 1) {
			enemyPos = new Vector3(0, 8, 0);
		}
		else {
			enemyPos = new Vector3(10, 8, 0);
		}
		createItem(Item[3], enemyPos, Quaternion.identity);
	}
	
}
